<template>
  <div class="agent-detail-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>代理详情</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border v-if="agentDetail">
          <el-descriptions-item label="代理ID">{{ agentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="代理名称">{{ agentDetail.name }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ agentDetail.phone || agentDetail.mobile || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="代理级别">{{ agentDetail.level_name || getLevelName(agentDetail.level) }}</el-descriptions-item>
          <el-descriptions-item label="上级代理">{{ agentDetail.parent_name || (agentDetail.parent ? agentDetail.parent.name : '无上级代理') }}</el-descriptions-item>
          <el-descriptions-item label="分成比例">{{ formatCommissionRate(agentDetail.commission_rate) }}%</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatDate(agentDetail.created_at || agentDetail.create_time) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="agentDetail.status === 1 ? 'success' : 'danger'">
              {{ agentDetail.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 激活码统计 -->
        <div class="section-title">激活码统计</div>
        <el-row :gutter="20" class="stats-cards">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">生成激活码总数</div>
              <div class="stats-card-value">{{ codeStats.total_count || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">已售卖激活码</div>
              <div class="stats-card-value">{{ codeStats.used_count || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">可用激活码数量</div>
              <div class="stats-card-value">{{ codeStats.unused_count || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">激活码使用率</div>
              <div class="stats-card-value">{{ usageRate }}%</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 销售统计 -->
        <div class="section-title">销售统计</div>
        <el-row :gutter="20" class="stats-cards">
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">今日销售</div>
              <div class="stats-card-value">{{ salesStats.today_used || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">昨日销售</div>
              <div class="stats-card-value">{{ salesStats.yesterday_used || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">本月销售</div>
              <div class="stats-card-value">{{ salesStats.month_used || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stats-card">
              <div class="stats-card-title">累计销售</div>
              <div class="stats-card-value">{{ salesStats.total_used || 0 }}</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 日期销售查询 -->
        <div class="section-title">日期销售查询</div>
        <div class="date-picker-container">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
          <el-button type="primary" @click="fetchSalesData">查询</el-button>
        </div>

        <!-- 销售数据表格 -->
        <el-table
          v-loading="tableLoading"
          :data="salesData"
          style="width: 100%; margin-top: 20px;"
          border
        >
          <el-table-column prop="date" label="日期" width="120" />
          <el-table-column prop="orderCount" label="卡密总数" width="100" />
          <el-table-column prop="activationCount" label="已激活数" width="100" />
          <el-table-column label="未激活数" width="100">
            <template #default="scope">
              {{ scope.row.orderCount - scope.row.activationCount }}
            </template>
          </el-table-column>
          <el-table-column label="激活率" width="100">
            <template #default="scope">
              {{ scope.row.conversionRate }}%
            </template>
          </el-table-column>
          <el-table-column label="佣金" width="120">
            <template #default="scope">
              {{ formatCurrency(scope.row.commission) }}
            </template>
          </el-table-column>
          <el-table-column prop="userCount" label="新增用户" width="100" />
          <el-table-column label="状态分布">
            <template #default="scope">
              <div v-if="scope.row.statusData">
                <el-tag type="success" size="small" v-if="scope.row.statusData['已售卖']">
                  已售卖: {{ scope.row.statusData['已售卖'] }}
                </el-tag>
                <el-tag type="info" size="small" v-if="scope.row.statusData['未售卖']" style="margin-left: 5px;">
                  未售卖: {{ scope.row.statusData['未售卖'] }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 图表展示 -->
        <div class="section-title">销售趋势</div>
        <div class="chart-container" ref="salesChartRef"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAgentDetail } from '@/api/agents'
import { getAgentActivationDetails, getAgentDashboardStats, getActivationCodesStatistics } from '@/api/statistics'
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const tableLoading = ref(false)
const agentDetail = ref(null)
const codeStats = ref({
  total_count: 0,
  used_count: 0,
  unused_count: 0,
  copied_count: 0,
  exported_count: 0
})
const salesStats = ref({
  today_used: 0,
  yesterday_used: 0,
  month_used: 0,
  last_month_used: 0,
  total_used: 0,
  month_generated: 0,
  last_month_generated: 0,
  stock_remaining: 0
})
const salesData = ref([])
const dateRange = ref([])
const salesChartRef = ref(null)
let salesChart = null

// 计算激活码使用率
const usageRate = computed(() => {
  if (!codeStats.value.total_count) return 0
  return Math.round((codeStats.value.used_count / codeStats.value.total_count) * 100)
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取代理ID
const agentId = computed(() => {
  return parseInt(route.params.id) || 0
})

// 返回列表页
const goBack = () => {
  router.push('/agent/list')
}

// 格式化货币
const formatCurrency = (value) => {
  return '¥' + parseFloat(value || 0).toFixed(2)
}

// 获取代理详情
const fetchAgentDetail = async () => {
  if (!agentId.value) return
  
  loading.value = true
  try {
    const res = await getAgentDetail(agentId.value)
    if (res.code === 0) {
      // 处理API返回的数据结构
      if (res.data && res.data.agent) {
        // 如果数据在agent字段中
        agentDetail.value = res.data.agent
      } else {
        // 直接使用返回的数据
        agentDetail.value = res.data
      }
      
      // 格式化佣金比例，确保显示为百分比
      if (agentDetail.value) {
        // 如果佣金比例是小数(0.x)，转换为百分比
        if (agentDetail.value.commission_rate && agentDetail.value.commission_rate < 1) {
          agentDetail.value.commission_rate = agentDetail.value.commission_rate * 100
        }
        
        // 确保手机号码字段统一
        if (!agentDetail.value.phone && agentDetail.value.mobile) {
          agentDetail.value.phone = agentDetail.value.mobile
        }
        
        // 确保上级代理名称字段统一
        if (!agentDetail.value.parent_name && agentDetail.value.parent) {
          agentDetail.value.parent_name = agentDetail.value.parent.name
        }
      }
    } else {
      ElMessage.error(res.message || '获取代理详情失败')
    }
  } catch (error) {
    console.error('获取代理详情失败', error)
    ElMessage.error('获取代理详情失败')
  } finally {
    loading.value = false
  }
}

// 获取激活码统计
const fetchCodeStats = async () => {
  if (!agentId.value) return
  
  try {
    const res = await getActivationCodesStatistics({ agent_id: agentId.value })
    if (res.code === 0) {
      codeStats.value = res.data
    } else {
      ElMessage.error(res.message || '获取激活码统计失败')
    }
  } catch (error) {
    console.error('获取激活码统计失败', error)
    ElMessage.error('获取激活码统计失败')
  }
}

// 获取销售统计
const fetchSalesStats = async () => {
  if (!agentId.value) return
  
  try {
    const res = await getAgentDashboardStats({ agent_id: agentId.value })
    if (res.code === 0 && res.data) {
      salesStats.value = res.data.code_stats || {}
    } else {
      ElMessage.error(res.message || '获取销售统计失败')
    }
  } catch (error) {
    console.error('获取销售统计失败', error)
    ElMessage.error('获取销售统计失败')
  }
}

// 获取销售数据
const fetchSalesData = async () => {
  if (!agentId.value || !dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择日期范围')
    return
  }
  
  tableLoading.value = true
  try {
    const params = {
      agent_id: agentId.value,
      start_date: dateRange.value[0],
      end_date: dateRange.value[1]
    }
    
    const res = await getAgentActivationDetails(params)
    if (res.code === 0) {
      // 确保数据格式正确
      if (res.data && res.data.list) {
        salesData.value = res.data.list.map(item => ({
          ...item,
          // 确保所有必要的字段都存在，兼容snake_case和camelCase
          date: item.date || '',
          orderCount: item.orderCount || item.order_count || 0,
          activationCount: item.activationCount || item.activation_count || 0,
          conversionRate: item.conversionRate || item.conversion_rate || 0,
          commission: item.commission || 0,
          userCount: item.userCount || item.user_count || 0,
          statusData: item.statusData || item.status_data || {}
        }))
      } else {
        // 如果返回的不是列表格式，可能是直接返回了数组
        salesData.value = Array.isArray(res.data) ? res.data : []
      }
      
      // 初始化图表
      initSalesChart()
    } else {
      ElMessage.error(res.message || '获取销售数据失败')
    }
  } catch (error) {
    console.error('获取销售数据失败', error)
    ElMessage.error('获取销售数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 初始化销售图表
const initSalesChart = () => {
  if (!salesData.value.length) return
  
  // 准备图表数据
  const dates = salesData.value.map(item => item.date)
  const orderCounts = salesData.value.map(item => item.orderCount)
  const activationCounts = salesData.value.map(item => item.activationCount)
  
  // 初始化图表
  if (!salesChart) {
    salesChart = echarts.init(salesChartRef.value)
  }
  
  const option = {
    title: {
      text: '销售趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['卡密总数', '已激活数']
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '卡密总数',
        type: 'line',
        data: orderCounts
      },
      {
        name: '已激活数',
        type: 'line',
        data: activationCounts
      }
    ]
  }
  
  salesChart.setOption(option)
}

// 格式化佣金比例
const formatCommissionRate = (rate) => {
  if (rate === undefined || rate === null) return 0
  
  // 如果佣金比例是小数(0.x)，转换为百分比
  if (rate < 1) {
    return (rate * 100).toFixed(2)
  }
  
  return rate.toFixed(2)
}

// 获取代理等级名称
const getLevelName = (level) => {
  const levelNames = {
    1: '普通代理',
    2: '高级代理',
    3: '区域代理',
    4: '总代理'
  }
  return levelNames[level] || '未知等级'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '未知'
  
  // 如果已经是格式化的日期字符串，直接返回
  if (typeof dateStr === 'string' && dateStr.includes('-')) {
    return dateStr
  }
  
  try {
    const date = new Date(dateStr)
    return date.toISOString().split('T')[0]
  } catch (e) {
    return '日期格式错误'
  }
}

// 页面初始化
onMounted(async () => {
  // 设置默认日期范围为最近一个月
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
  
  // 获取数据
  await fetchAgentDetail()
  await fetchCodeStats()
  await fetchSalesStats()
  await fetchSalesData()
  
  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    if (salesChart) {
      salesChart.resize()
    }
  })
})
</script>

<style scoped>
.agent-detail-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.section-title {
  font-size: 18px;
  font-weight: 500;
  margin: 30px 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
.stats-cards {
  margin-bottom: 20px;
}
.stats-card {
  height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.stats-card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}
.stats-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.date-picker-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}
.chart-container {
  height: 400px;
  margin-top: 20px;
}
</style> 